package com.intretech.tj.global.tools;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json 工具类
 */
public class JSONTool {
    /**
     * 将对象啊转为json字符串<br/>
     * 私有变量需要get函数
     *
     * @param object 对象
     * @return json字符串
     */
    public static String toJSONString(Object object) {
        // 创建一个ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 将Person对象转换为格式化的JSON字符串
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 将json字符串转为对象
     *
     * @param json json字符串
     * @param clazz 对象类型
     * @return 对象
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
